﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Markup;
using System.Xml.Linq;
using HandyControl.Collections;
using Newtonsoft.Json.Linq;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using YJTMedicalAideManage.Cores;
using YJTMedicalAideManage.Cores.Events;
using YJTMedicalAideManage.Cores.Globals;
using YJTMedicalAideManage.Cores.Models;
using YJTMedicalAideManage.Cores.Servers;
using YJTMedicalAideManage.MAM.Model;

namespace YJTMedicalAideManage.MAM.ViewModels
{
    public class AddOrEditPagesDialogViewModel : InheritBase, IDialogAware
    {
        #region 公用
        private readonly ApiService _apiService;
        public DialogParameters DialogParameters { get; set; }
        public bool DialogResult { get; private set; }
        public string Title => "";

        #endregion

        #region 属性
        private AssAddDto _editedData;

        public AssAddDto EditedData
        {
            get => _editedData;
            set
            {
                _editedData = value;
                RaisePropertyChanged();
            }
        }
        private AreaInfo _areaInfo;

        public AreaInfo AreaInfo
        {
            get => _areaInfo;
            set
            {

                _areaInfo = value;
                RaisePropertyChanged();
            }
        }

        private bool _isEnableds;

        public bool IsEnableds
        {
            get => _isEnableds;
            set
            {

                _isEnableds = value;
                RaisePropertyChanged();
            }
        }

        private string userTitle;

        public string UserTitle
        {
            get => userTitle;
            set
            {

                userTitle = value;
                RaisePropertyChanged();
            }
        }
        #endregion

        #region 集合

        public ObservableCollection<adddress> CityList { get; set; }
        public ObservableCollection<adddress> AreaList { get; set; }
        private ObservableCollection<adddress> _provinceList;
        public ObservableCollection<adddress> ProvinceList
        {
            get => _provinceList;
            set
            {
                _provinceList = value;
                RaisePropertyChanged();
            }
        }
        private ObservableCollection<adddress> _filteredCityList;
        public ObservableCollection<adddress> FilteredCityList
        {
            get => _filteredCityList;
            set
            {
                _filteredCityList = value;
                RaisePropertyChanged();
            }
        }

        private ObservableCollection<adddress> _filteredAreaList;
        public ObservableCollection<adddress> FilteredAreaList
        {
            get => _filteredAreaList;
            set
            {
                _filteredAreaList = value;
                RaisePropertyChanged();
            }
        }
        #endregion

        #region 事件
        public event Action<IDialogResult> RequestClose;
        #endregion

        #region 命令
        public DelegateCommand ConfirmCommand { get; }
        public DelegateCommand CancelCommand { get; }
        #endregion
        public AddOrEditPagesDialogViewModel()
        {
            _apiService = new ApiService();
            AddDressEvent.Instance.Subscribe(AddDress);
            AddDressEvent.Instance.Subscribes(AddCtiyDress);
            DialogParameters = new DialogParameters();
            AreaInfo = new AreaInfo();
            EditedData = new AssAddDto();
            ProvinceList = new ObservableCollection<adddress>();
            ConfirmCommand = new DelegateCommand(() =>
            {
                try
                {
                    if (string.IsNullOrEmpty(EditedData.Tel) || !GlobalApp.Instance.IsValidPhoneNumber(EditedData.Tel) == true)
                    {
                        MessgaeWarning("手机号位数不足，请重新填写后提交！");
                        return;
                    }
                    if (string.IsNullOrEmpty(EditedData.Username) || EditedData.Username.Trim() == "")
                    {
                        MessgaeWarning("账号为空，请重新填写后提交！");
                        return;
                    }
                    if (string.IsNullOrEmpty(EditedData.Name) || EditedData.Name.Trim() == "")
                    {
                        MessgaeWarning("姓名为空，请重新填写后提交！");
                        return;
                    }
                    if ((EditedData.Password == null || !GlobalApp.Instance.IsValidPassword(EditedData.Password) == true)&&EditedData.Password != OriginalData.Pwd)
                    {
                        MessgaeWarning("需包含大小写字母、数字，不少于8位,不支持其它字符，请重新填写后提交！");
                        return;
                    }
                    if (AreaInfo.Province!=null && !string.IsNullOrEmpty(AreaInfo.Province.provinceName))
                    {
                        if ((AreaInfo.City == null && AreaInfo.Area == null) ||(string.IsNullOrEmpty(AreaInfo.City.cityName) || string.IsNullOrEmpty(AreaInfo.Live_address)))
                        {
                            MessgaeWarning("地址有一项填写时,其它项为必填,请重新填写后提交！");
                            return;
                        }
                    }
                    if (!string.IsNullOrEmpty(AreaInfo.Live_address))
                    {
                        if (AreaInfo.Province == null || string.IsNullOrEmpty(AreaInfo.Province.provinceName))
                        {
                            MessgaeWarning("地址有一项填写时,其它项为必填,请重新填写后提交！");
                            return;
                        }

                        if (AreaInfo.City == null || string.IsNullOrEmpty(AreaInfo.City.cityName))
                        {
                            MessgaeWarning("地址有一项填写时,其它项为必填,请重新填写后提交！");
                            return;
                        }
                    }
                    if (!_isMunicipality && AreaInfo.Area!= null && string.IsNullOrEmpty(AreaInfo.Area.areaName))
                    {
                        MessgaeWarning("地址有一项填写时,其它项为必填,请重新填写后提交！");
                        return;
                    }
                    var ProvinceName = AreaInfo.Province == null ? "" : AreaInfo.Province.provinceName;
                    var CityName = AreaInfo.City == null ? "" : AreaInfo.City.cityName;
                    var AreaName = AreaInfo.Area == null ? "" : AreaInfo.Area.areaName;
                    var ProvinceCode = AreaInfo.Province == null ? "" : AreaInfo.Province.provinceId;
                    var CityCode = AreaInfo.City == null ? "" : AreaInfo.City.cityId;
                    var AreaCode = AreaInfo.Area == null ? "" : AreaInfo.Area.areaId;
                    AreaInfo.Live_address = $"{AreaInfo.Live_address}";
                    EditedData.LiveProvinceId = ProvinceCode;
                    EditedData.LiveCityId = CityCode;
                    EditedData.LiveAreaId = AreaCode;
                    EditedData.LiveArea = AreaName;
                    EditedData.LiveProvince = ProvinceName;
                    EditedData.LiveCity = CityName;
                    EditedData.LiveAddress = AreaInfo.Live_address;
                    DialogParameters.Add("EditedData", EditedData); // 传递关闭时的状态
                    RequestClose?.Invoke(new DialogResult(DialogResult ? ButtonResult.OK : ButtonResult.OK, DialogParameters));
                }
                catch (Exception ex) 
                {
                    MessgaeError(ex.Message);
                    return;
                }  
            });

            CancelCommand = new DelegateCommand(() =>
            {
                RequestClose?.Invoke(new DialogResult(DialogResult ? ButtonResult.Cancel : ButtonResult.Cancel, null));
            });
        }
        private async Task FilterCityList(string provinceCode)
        {
            if (string.IsNullOrEmpty(provinceCode))
            {
                FilteredCityList = new ObservableCollection<adddress>();
            }
            else
            {
                var Cdata = await _apiService.GetAllCityAsync(provinceCode);
                var Adata = await _apiService.GetAllAreaAsync(provinceCode);
                if (Cdata.msg.Contains("登录认证失败"))
                {
                    var data1 = await _apiService.logoutAsync(GlobalApp.Instance.Manager_Id);
                    CloseStringEvent.Instance.PushMessage("");
                    return;
                }
                if (Adata.msg.Contains("登录认证失败"))
                {
                    var data1 = await _apiService.logoutAsync(GlobalApp.Instance.Manager_Id);
                    CloseStringEvent.Instance.PushMessage("");
                    return;
                }
                CityList = new ObservableCollection<adddress>();
                AreaList = new ObservableCollection<adddress>();
                foreach (var item in Cdata.data)
                {
                    CityList.Add(new adddress() { cityName = item.cityName, cityId = item.cityId });
                }
                foreach (var item in Adata.data)
                {
                    AreaList.Add(new adddress() { cityName = item.cityName, cityId = item.cityId });
                }
                FilteredCityList = new ObservableCollection<adddress>(CityList);
                if (FilteredCityList.Count == 0)
                {
                    FilteredCityList = new ObservableCollection<adddress>(AreaList);
                    _isMunicipality = true;
                    _provinceCode = provinceCode;
                    return;
                }
                _provinceCode = provinceCode;
                _isMunicipality = false;
            }
        }
        private bool _isMunicipality = false;
        private string _provinceCode;
        private async Task FilterAreaList(string cityCode)
        {
            if (_isMunicipality == true)
            {
                FilteredAreaList = new ObservableCollection<adddress>();
                return;
            }
            if (string.IsNullOrEmpty(cityCode))
            {
                FilteredAreaList = new ObservableCollection<adddress>();
            }
            else
            {
                AreaList = new ObservableCollection<adddress>();
                var Adata = await _apiService.GetAllAreaAsync(cityCode);
                if (Adata.msg.Contains("登录认证失败"))
                {
                    var data1 = await _apiService.logoutAsync(GlobalApp.Instance.Manager_Id);
                    CloseStringEvent.Instance.PushMessage("");
                    return;
                }
                foreach (var item in Adata.data)
                {
                    AreaList.Add(new adddress() { areaName = item.areaName, areaId = item.areaId });
                }
                FilteredAreaList = new ObservableCollection<adddress>(AreaList);
            }
        }
        private async void AddDress(adddress adddress)
        {
            if (adddress != null && !string.IsNullOrEmpty(adddress.provinceName))
            {
                await FilterCityList(adddress.provinceId);
            }
            else
            {
                FilteredCityList = new ObservableCollection<adddress>();
            }

        }
        private async void AddCtiyDress(adddress adddress)
        {
            if (adddress != null && !string.IsNullOrEmpty(adddress.cityId))
            {
                await FilterAreaList(adddress.cityId);
            }
            else
            {
                FilteredAreaList = new ObservableCollection<adddress>();
            }

        }
        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }
        private MAMDto OriginalData = new MAMDto();
        private bool isbool = false;
        private async void init() 
        {
            try
            {
                if (EditedData != null)
                {
                    FilteredCityList = new ObservableCollection<adddress>();
                    FilteredAreaList = new ObservableCollection<adddress>();
                    if (EditedData.LiveProvinceId != null)
                    {
                        ProvinceList = new ObservableCollection<adddress>(GlobalApp.Instance.ProvinceList);
                        AreaInfo.Province = ProvinceList.FirstOrDefault(s => s.provinceId == EditedData.LiveProvinceId);
                    }
                    if (EditedData.LiveAddress != null)
                    {
                        AreaInfo.Live_address = EditedData.LiveAddress;
                    }
                    if (AreaInfo.Province == null)
                    {
                        StatusMamEvent.Instance.PushMessage("");
                    }
                    if (!string.IsNullOrEmpty(EditedData.LiveCityId))
                    {
                        if (AreaInfo.Province != null && !string.IsNullOrEmpty(AreaInfo.Province.provinceId))
                        {
                            var data = await _apiService.GetAllCityAsync(AreaInfo.Province.provinceId);
                            foreach (var item in data.data)
                            {
                                FilteredCityList.Add(new adddress { cityName = item.cityName, cityId = item.cityId });
                            }
                            AreaInfo.City = FilteredCityList.FirstOrDefault(s => s.cityId == EditedData.LiveCityId);
                        }
                    }
                    if (!string.IsNullOrEmpty(EditedData.LiveAreaId) && AreaInfo.City != null&&!string.IsNullOrEmpty(AreaInfo.City.cityId))
                    {
                        var data = await _apiService.GetAllAreaAsync(AreaInfo.City.cityId);
                        foreach (var item in data.data)
                        {
                            FilteredAreaList.Add(new adddress { areaName = item.areaName, areaId = item.areaId });
                        }
                        AreaInfo.Area = FilteredAreaList.FirstOrDefault(s => s.areaId == EditedData.LiveAreaId);
                    }
                }
            }
            finally
            {

            }
        }
        public void OnDialogOpened(IDialogParameters parameters)
        {
            IsEnableds = parameters.GetValue<bool>("IsEnableds");
            if (IsEnableds)
            {
                EditedData = new AssAddDto();
                EditedData.OperatorId = GlobalApp.Instance.OperatorId ?? "";
                EditedData.TenantName = GlobalApp.Instance.ClinicName ?? "";
                UserTitle = "添加";
                ProvinceList = new ObservableCollection<adddress>(GlobalApp.Instance.ProvinceList);
            }
            else
            {
                UserTitle = "编辑";
                OriginalData = parameters.GetValue<MAMDto>("EditedData");
                isbool = false;
                 EditedData = new AssAddDto()
                {
                    TenantName = OriginalData.TenantName,
                    LiveProvinceId = OriginalData.LiveProvinceId,
                    LiveAddress = OriginalData.Live_address,
                    LiveAreaId = OriginalData.LiveAreaId,
                    LiveCityId = OriginalData.LiveCityId,
                    TenantId = OriginalData.TenantId,
                    Name = OriginalData.Name,
                    Username = OriginalData.Username,
                    Tel = OriginalData.Tel,
                    OperatorId = OriginalData.OperatorId,
                    Password = OriginalData.Pwd,
                    RoleId = GlobalApp.Instance.Role_Id,
                    Scale = GlobalApp.Instance.Scale,

                };
                StatusMamEvent.Instance.PushMessage("编辑");
                init();
            }


        }

    }
}
